<template>
  <div class="container posts-create-page">
    <h4>{{ isEdit ? '编辑文章' : '新建文章' }}</h4>
    <uploader
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      action="/upload"
      :uploaded="uploadData"
      :beforeUpload="beforeUpload"
      @on-upload-success="onUploadSuccess"
      @on-upload-error="onUploadError"
    >
      <h2>点击上传头图</h2>
      <template #loading>
        <div class="d-flex lh-lg">
          <div class="spinner-border text-secondary">
            <span class="visually-hidden">Loading...</span>
          </div>
          <h2>正在上传...</h2>
        </div>
      </template>
      <template #success="{ data }">
        <img :src="data[0].url" alt="" />
      </template>
    </uploader>
    <validate-form ref="formRef" @form-submit="handleSubmit">
      <validate-form-item label="文章标题">
        <validate-input
          type="text"
          v-model="state.title"
          :rules="rules.title"
          placeholder="请输入文章标题"
        ></validate-input>
      </validate-form-item>
      <validate-form-item label="文章内容">
        <validate-input
          type="textarea"
          rows="10"
          v-model="state.content"
          :rules="rules.content"
          placeholder="请输入文章内容"
        ></validate-input>
      </validate-form-item>
      <template #submit>
        <button class="btn btn-primary" @click.prevent="handleSubmit">
          {{ isEdit ? '更新文章' : '发表文章' }}
        </button>
      </template>
    </validate-form>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, DefineComponent, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import ValidateInput from '@/components/ValidateInput.vue'
import ValidateForm from '@/components/ValidateForm.vue'
import ValidateFormItem from '@/components/ValidateFormItem.vue'
import Uploader from '@/components/Uploader.vue'
import messageCreate from '@/components/MessageCreate'
import { beforeUploadCheck } from '@/utils'
import {
  IPostsProp,
  IRules,
  IStore,
  IResponseData,
  IImageProp
} from '@/types/index'
export default defineComponent({
  name: 'PostsCreate',
  components: {
    ValidateInput,
    ValidateForm,
    ValidateFormItem,
    Uploader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore<IStore>()
    const isEdit = !!route.query.id
    let state = reactive<IPostsProp>({
      title: '',
      content: '',
      image: '',
      column: '',
      author: ''
    })
    let uploadData = ref<IImageProp[]>([])
    const rules: IRules = {
      title: [
        { type: 'required', message: '请输入文章标题' },
        { type: 'range', max: 20, message: '不能大于20个字符' }
      ],
      content: [{ type: 'required', message: '请输入文章内容' }]
    }
    const beforeUpload = (file: File) => {
      const { passed, error } = beforeUploadCheck(file, {
        size: 1,
        format: ['image/png']
      })
      if (error === 'size') {
        messageCreate({
          type: 'danger',
          message: '图片大小不对'
        })
      } else if (error === 'format') {
        messageCreate({
          type: 'danger',
          message: '图片格式不对'
        })
      }
      return passed
    }
    const onUploadSuccess = (res: IResponseData<IImageProp>) => {
      if (res.data._id) {
        state.image = res.data._id
      }
      messageCreate({
        type: 'success',
        message: '上传成功'
      })
    }
    const onUploadError = () => {
      messageCreate({
        type: 'danger',
        message: `上传失败`
      })
    }
    const formRef = ref<null | DefineComponent>(null)
    const handleSubmit = () => {
      const valid: boolean = formRef.value?.handleSubmit()
      if (valid) {
        const { column, _id } = store.state.user
        if (column) state.column = column
        if (_id) state.author = _id
        const { image, ...other } = state
        const params = image ? state : other
        const actionName = isEdit ? 'updatePosts' : 'createPosts'
        const sendData = isEdit
          ? { id: route.query.id, payload: params }
          : params
        store.dispatch(actionName, sendData).then(() => {
          messageCreate(
            {
              type: 'success',
              message: '文章发表成功，2秒后跳转专栏页'
            },
            () => {
              router.push({
                name: 'Column',
                params: {
                  id: column
                }
              })
            }
          )
        })
      }
    }
    onMounted(() => {
      if (isEdit) {
        store.dispatch('getPosts', route.query.id).then((res: IPostsProp) => {
          state.title = res.title
          state.content = res.content || ''
          if (res.image) {
            const image = res.image as IImageProp
            uploadData.value.push(image)
          }
        })
      }
    })
    return {
      formRef,
      state,
      rules,
      uploadData,
      isEdit,
      beforeUpload,
      onUploadSuccess,
      onUploadError,
      handleSubmit
    }
  }
})
</script>
<style scoped>
.posts-create-page /deep/ .file-upload-container {
  height: 200px;
  cursor: pointer;
}
.posts-create-page /deep/ .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
